package net.kazed.nextaction.task;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;

import net.kazed.nextaction.NextActionApplication;
import net.kazed.nextaction.R;
import net.kazed.nextaction.context.activity.ContextsActivity;
import net.kazed.nextaction.database.ContextCache;
import net.kazed.nextaction.database.GtdContext;
import net.kazed.nextaction.database.Task;

public class TaskEditorActivity extends Activity {

    private static final String cTag = "TaskEditorActivity";
    
    private static final int MENU_REVERT = Menu.FIRST;
    private static final int MENU_DELETE = Menu.FIRST + 1;
   
    private Cursor cursor;
    private boolean isNew;
    private Uri itemUri;
    private long selectedContextId;
    private Task originalTask;
    private List<GtdContext> contextList;

    private EditText nameWidget;
    private CheckBox completedWidget;
    private Spinner contextSpinner;
    private EditText noteWidget;
        
    @Override
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        
        final Intent intent = getIntent();
        final String action = intent.getAction();
        selectedContextId = intent.getLongExtra(GtdContext.SELECTED_CONTEXT_ID, 0);
        if (action.equals(Intent.ACTION_EDIT)) {
            isNew = false;
            itemUri = intent.getData();
        } else if (action.equals(Intent.ACTION_INSERT)) {
           isNew = true;
           itemUri = getContentResolver().insert(Task.CONTENT_URI, null);

           if (itemUri == null) {
              Log.e(cTag, "Failed to insert new item into "
                    + getIntent().getData());
              finish();
              return;
           }
           // KZ - put this in onSaveInstanceState or onPause ?
          Bundle bundle = new Bundle();
          bundle.putString(ContextsActivity.SELECTED_ITEM, itemUri.toString());
          Intent mIntent = new Intent();
          mIntent.putExtras(bundle);
          setResult(RESULT_OK, mIntent);
        } else {
            finish();
            return;
        }

        cursor = managedQuery(itemUri, Task.FULL_PROJECTION.getFieldNames(), null, null, null);
        
        setContentView(R.layout.task_editor);
        nameWidget = (EditText) findViewById(R.id.description);
        completedWidget = (CheckBox) findViewById(R.id.completed_checkbox);
        contextSpinner = (Spinner) findViewById(R.id.context_spinner);
        noteWidget = (EditText) findViewById(R.id.notes);
        
        NextActionApplication application = (NextActionApplication) getApplication();
        ContextCache contextCache = application.getContextCache(); //new ContextCache(getContentResolver());

        List<GtdContext> contextsFromTree = contextCache.getFlattenedContextTree();
        contextList = new ArrayList<GtdContext>(contextsFromTree.size() + 1);
        String inboxTitle = getResources().getString(R.string.inbox_title);
        GtdContext inboxContext = new GtdContext(inboxTitle);
        contextList.add(inboxContext);
        contextList.addAll(contextCache.getFlattenedContextTree());

        ContentResolver resolver = getContentResolver();
        List<String> contextNameList = new ArrayList<String>(contextList.size());
        int i = 0;
        int selectedContextPosition = 0;
        for (Iterator<GtdContext> contextIterator = contextList.iterator(); contextIterator.hasNext();) {
           GtdContext context = (GtdContext) contextIterator.next();
           contextNameList.add(context.getAbsoluteContextPath(resolver, "/"));
           if (context.getId() != null && selectedContextId == context.getId()) {
              selectedContextPosition = i;
           }
           i++;
        }
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item,
              android.R.id.text1, contextNameList);
        contextSpinner.setAdapter(arrayAdapter);
        contextSpinner.setSelection(selectedContextPosition, true);
    }
    
    @Override
    protected void onResume() {
        Log.d(cTag, "onResume+");
        super.onResume();

        if (cursor != null) {
            cursor.moveToFirst();
            if (isNew) {
               setTitle(R.string.title_new_task);
            } else {
                setTitle(R.string.title_edit_task);
            }

            originalTask = new Task(cursor);
            populateFields(originalTask);
        } else {
            setTitle(getText(R.string.error_title));
            nameWidget.setText(getText(R.string.error_message));
        }
        
        nameWidget.selectAll();
    }

   private void populateFields(Task task) {
      nameWidget.setTextKeepState(task.getDescription() == null ? "" : task.getDescription());
      completedWidget.setChecked(task.getComplete());
      noteWidget.setTextKeepState(task.getDetails());
      
      Integer contextId = task.getContextId();
      if (contextId != null) {
         int i = 0;
         for (Iterator<GtdContext> contextIterator = contextList.iterator(); contextIterator.hasNext();) {
            GtdContext context = contextIterator.next();
            if (contextId.equals(context.getId())) {
               contextSpinner.setSelection(i);
               break;
            }
            i++;
         }
      }
   }
    
    @Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent data) {
    	Log.d(cTag, "Got resultCode " + resultCode + " with data " + data);		
	}
    
    @Override
    protected void onPause() {
        super.onPause();
        if (cursor != null) {
            Task task = new Task(cursor);
            if (isNew) {
               task.setContextId((int) selectedContextId);
            }
            task.setDescription(nameWidget.getText().toString());
            task.setComplete(completedWidget.isChecked());
            task.setDetails(noteWidget.getText().toString());
            int contextPosition = contextSpinner.getSelectedItemPosition();
            if (contextPosition < contextList.size()) {
               GtdContext context = contextList.get(contextPosition);
               task.setContextId(context.getId());
            }
            ContentValues values = new ContentValues();
            task.toValues(values);
            getContentResolver().update(itemUri, values, null, null);
        }
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
       Resources resources = getResources();
       menu.add(0, MENU_REVERT, 0, resources.getString(R.string.menu_revert))
          .setIcon(android.R.drawable.ic_menu_revert).setAlphabeticShortcut('r');
       menu.add(0, MENU_DELETE, 1, resources.getString(R.string.menu_delete))
          .setIcon(android.R.drawable.ic_menu_delete).setAlphabeticShortcut('d');
       return super.onCreateOptionsMenu(menu);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
       switch (item.getItemId()) {
       case MENU_REVERT:
          populateFields(originalTask);
          break;
       case MENU_DELETE:
          getContentResolver().delete(itemUri, null, null);
          finish();
          break;
       }
       return super.onOptionsItemSelected(item);
    }
    
    /**
     * Take care of deleting a context.  Simply deletes the entry.
     */
    protected void deleteItem() {
       nameWidget.setText("");
    }
    
}
